//
//  DetailListViewController.m
//  SAYAKA_Kitchen
//
//  Created by Rei on 13/07/20.
//  Copyright (c) 2013年 hackathon. All rights reserved.
//

#import "DetailListViewController.h"
#import "FloorCheckViewController.h"
#import "DetailCell.h"
#import "ItemEntity.h"
@interface DetailListViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *detailTableView;
@property (weak, nonatomic) IBOutlet UILabel *sumPrice;
@property (strong, nonatomic) UILabel *emptyLabel;
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
@property (strong, nonatomic) NSMutableArray *tableNumberArray;
@property (strong, nonatomic) NSMutableArray *orderArray;
@property (copy, nonatomic) NSArray *crntOrderArray;
@property (weak, nonatomic) IBOutlet UIButton *paymentBtn;
@property (weak, nonatomic) IBOutlet UIButton *floorCheckBtn;
- (IBAction)pushPaymentBtn:(id)sender;
- (IBAction)pushFloorCheckBtn:(id)sender;


@end

@implementation DetailListViewController

#pragma mark - Managing the detail item

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        // Update the view.
        [self configureView];
    }
    [self configureView];
    if (self.masterPopoverController != nil) {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }
}

//注文一覧画面を更新する
- (void)configureView
{
    // Update the user interface for the detail item.
    
    if (self.detailItem) {
        int tableNumberIndex = 0;
        for (int i = 0; i < [self.tableNumberArray count]; i++) {
            if ([[self.tableNumberArray objectAtIndex:i] integerValue] == [self.detailItem integerValue]) {
                tableNumberIndex = i;
            }
        }
        if ([self.orderArray count] > 0) {
            self.emptyLabel.text = nil;
            self.emptyLabel = nil;
            self.crntOrderArray = [self.orderArray objectAtIndex:tableNumberIndex];
            
            [self.detailTableView reloadData];
            
            int sum = 0;
            for (id it in self.crntOrderArray) {
                ItemEntity *item = (ItemEntity *)it;
                if (item.isProvided) {
                    sum = sum + (item.price * item.numberOfItems);
                }
            }
            self.title = [NSString stringWithFormat:@"注文一覧: %d番テーブル", [self.detailItem intValue]];
            self.sumPrice.text = [NSString stringWithFormat:@"%d", sum];
        } else {
            self.sumPrice.text = @"---";
        }
    }
    
    if ([self.tableNumberArray count] == 0) {
        self.title = @"注文一覧";
        self.emptyLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 300, 320, 44)];
        self.emptyLabel.text = @"現在注文はありません。";
        [self.emptyLabel setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:self.emptyLabel];
    }
    [self reloadPaymentBtnStatus];
}


#pragma mark view lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"注文一覧";
        self.crntOrderArray = nil;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.detailTableView.dataSource = self;
    self.detailTableView.delegate = self;
    self.detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.detailTableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:@"DetailCell"];
    
    [self reloadPaymentBtnStatus];
    self.tableNumberArray = [NSMutableArray array];
    self.orderArray = [NSMutableArray array];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(addNewOrder:)
                                                 name:@"newOrderArrival"
                                               object:nil];
    
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                                                               target:self
                                                                               action:@selector(configureView)];
    self.navigationItem.rightBarButtonItem = addButton;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Split view
- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    [self.navigationItem setLeftBarButtonItem:nil animated:YES];
    self.masterPopoverController = nil;
}

//新規注文時に呼ばれる
- (void)addNewOrder:(NSNotification*)notification {    
    BOOL isFirstOrder = YES;
    int tableNumberIndex = 0;

    for (int i = 0; i < [self.tableNumberArray count]; i++) {
        if ([self.tableNumberArray objectAtIndex:i] == [[notification userInfo] objectForKey:@"table_number"]) {
            isFirstOrder = NO;
            tableNumberIndex = i;
        }
    }
    
    //初回注文時は注文データ格納用空配列を用意する
    if (isFirstOrder) {
        [self.tableNumberArray insertObject:[[notification userInfo] objectForKey:@"table_number"] atIndex:0];
        tableNumberIndex = 0;
        NSMutableArray *array = [NSMutableArray array];
        [self.orderArray insertObject:array atIndex:0];
    }

    //注文内容を格納
    NSArray *items = [[notification userInfo] objectForKey:@"items"];
    for (int i = 0; i < [items count]; i++) {
        ItemEntity *item = [[ItemEntity alloc] init];
        item.name = [[items objectAtIndex:i] objectForKey:@"name"];
        item.price = [[[items objectAtIndex:i] objectForKey:@"price"] intValue];
        item.numberOfItems = [[[items objectAtIndex:i] objectForKey:@"num_of_items"] intValue];
        item.isProvided = NO;
        [[self.orderArray objectAtIndex:tableNumberIndex] insertObject:item atIndex:0];
    }
}

#pragma mark - TableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self.crntOrderArray count]) {
        return [self.crntOrderArray count];
    }
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"DetailCell";
    
    DetailCell *cell = [self.detailTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[DetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if ([self.crntOrderArray count]) {
        ItemEntity *item = [self.crntOrderArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = item.name;
        cell.unitPriceLabel.text = [NSString stringWithFormat:@"%d", item.price];
        cell.quantityLabel.text = [NSString stringWithFormat:@"%d", item.numberOfItems];
        cell.totalPriceLabel.text = [NSString stringWithFormat:@"%d", (item.price * item.numberOfItems)];
        if (item.isProvided) {
            cell.providerLabel.text = nil;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        } else {
            cell.providerLabel.text = @"未";
            cell.providerLabel.textColor = [UIColor redColor];
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        }
    } else {
        UITableViewCell *emptyCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        emptyCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return emptyCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ItemEntity *item = [self.crntOrderArray objectAtIndex:indexPath.row];
    item.isProvided = YES;
    [self configureView];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 0 && buttonIndex == 1) {
        int tableNumberIndex = 0;
        for (int i = 0; i < [self.tableNumberArray count]; i++) {
            if ([[self.tableNumberArray objectAtIndex:i] intValue] == [self.detailItem intValue]) {
                tableNumberIndex = i;
            }
        }
        
        if ([self.tableNumberArray count] > 1) {
            [self.tableNumberArray removeObjectAtIndex:tableNumberIndex];
            [self.orderArray removeObjectAtIndex:tableNumberIndex];
            if ([self.tableNumberArray count] > tableNumberIndex-1) {
                self.crntOrderArray = [self.orderArray objectAtIndex:tableNumberIndex-1];
                self.detailItem = [self.tableNumberArray objectAtIndex:tableNumberIndex-1];
            } else {
                self.crntOrderArray = [self.orderArray objectAtIndex:tableNumberIndex];
                self.detailItem = [self.tableNumberArray objectAtIndex:tableNumberIndex];
            }
        } else {
            self.tableNumberArray = [NSMutableArray array];
            self.orderArray = [NSMutableArray array];
            self.crntOrderArray = nil;
        }
        
        [self configureView];
        [self.delegate detailListViewController:self clearOrderForNumberOfTable:tableNumberIndex];
        [self reloadPaymentBtnStatus];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"会計"
                                                            message:@"会計処理が正常に終了しました。"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
        alertView.tag = 1;
        [alertView show];
    }
}

- (IBAction)pushPaymentBtn:(id)sender {
    NSString *message = [NSString stringWithFormat:@"%d番テーブルの会計を行いますか？", [self.detailItem intValue]];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"会計"
                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"OK", nil];
    alertView.tag = 0;
    [alertView show];
}

- (IBAction)pushFloorCheckBtn:(id)sender {
    FloorCheckViewController *floorCheckViewController = [[FloorCheckViewController alloc] initWithNibName:@"FloorCheckViewController" bundle:nil];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:floorCheckViewController];

    [navigationController setModalPresentationStyle:UIModalPresentationPageSheet];
    [self presentViewController:navigationController animated:YES completion:nil];
}

- (void)reloadPaymentBtnStatus {
    if ([self.tableNumberArray count] > 0) {
        [self.paymentBtn setEnabled:YES];
    } else {
        [self.paymentBtn setEnabled:NO];
    }
    [self.detailTableView reloadData];
}
@end